package parser

import (
	"github.com/fatih/color"
	"github.com/hashicorp/hcl/v2"
	"github.com/hashicorp/hcl/v2/gohcl"
	"github.com/ihaiker/tfwrapper/internal/config"
	"github.com/ihaiker/tfwrapper/internal/eval"
	"github.com/ihaiker/tfwrapper/internal/logger"
)

func parseGenerator(options config.Running, file *hcl.File) ([]*config.Generator, hcl.Diagnostics) {
	log := logger.Logger(options)

	content, _, diags := file.Body.PartialContent(&hcl.BodySchema{
		Blocks: []hcl.BlockHeaderSchema{
			{Type: "generate", LabelNames: []string{"name"}},
		},
	})
	if diags.HasErrors() || len(content.Blocks) == 0 {
		return nil, diags
	}
	ctx, diags := eval.CreateEvalContext(options)
	if diags.HasErrors() {
		return nil, diags
	}

	generators := make([]*config.Generator, len(content.Blocks))
	for idx := 0; idx < len(generators); idx++ {
		gen := new(config.Generator)
		blockBody := content.Blocks[idx].Body
		diags = gohcl.DecodeBody(blockBody, ctx.EvalContext, gen)
		if diags.HasErrors() {
			return nil, diags
		}
		gen.Name = content.Blocks[idx].Labels[0]
		generators[idx] = gen
	}

	for _, g := range generators {
		log.Debugf("found generator: %s", color.HiMagentaString(g.Name))
	}
	return generators, nil
}
